import { create } from 'zustand';
import { persist } from 'zustand/middleware';

export type Plan = {
  id: string;
  title: string;
  description?: string;
  startDate: Date;
  endDate?: Date;
  isCompleted: boolean;
  userId: string;
};

export type CheckIn = {
  id: string;
  date: Date;
  note?: string;
  imageUrl?: string;
  planId: string;
};

type State = {
  currentUser: {
    id: string;
    name: string;
    email: string;
    image?: string;
  } | null;
  plans: Plan[];
  checkIns: CheckIn[];
  playCongratulationSound: boolean;
  loading: boolean;
  setCurrentUser: (user: State['currentUser']) => void;
  setPlans: (plans: Plan[]) => void;
  addPlan: (plan: Plan) => void;
  updatePlan: (id: string, plan: Partial<Plan>) => void;
  deletePlan: (id: string) => void;
  setCheckIns: (checkIns: CheckIn[]) => void;
  addCheckIn: (checkIn: CheckIn) => void;
  deleteCheckIn: (id: string) => void;
  setPlayCongratulationSound: (play: boolean) => void;
  setLoading: (loading: boolean) => void;
};

export const useStore = create<State>()(
  persist(
    (set) => ({
      currentUser: null,
      plans: [],
      checkIns: [],
      playCongratulationSound: false,
      loading: false,
      setCurrentUser: (user) => set({ currentUser: user }),
      setPlans: (plans) => set({ plans }),
      addPlan: (plan) => set((state) => ({ plans: [...state.plans, plan] })),
      updatePlan: (id, updatedPlan) =>
        set((state) => ({
          plans: state.plans.map((plan) =>
            plan.id === id ? { ...plan, ...updatedPlan } : plan
          ),
        })),
      deletePlan: (id) =>
        set((state) => ({
          plans: state.plans.filter((plan) => plan.id !== id),
        })),
      setCheckIns: (checkIns) => set({ checkIns }),
      addCheckIn: (checkIn) =>
        set((state) => ({ checkIns: [...state.checkIns, checkIn] })),
      deleteCheckIn: (id) =>
        set((state) => ({
          checkIns: state.checkIns.filter((checkIn) => checkIn.id !== id),
        })),
      setPlayCongratulationSound: (play) => set({ playCongratulationSound: play }),
      setLoading: (loading) => set({ loading }),
    }),
    {
      name: 'daily-plan-storage',
    }
  )
); 